part of 'index.dart';

class ITabBar extends StatefulWidget {
  const ITabBar({
    super.key,
    required this.ctrl,
    this.isScrollable = false,
    required this.tabs,
    this.config,
  });
  final TabController? ctrl;
  final TabbarConfig? config;
  final bool isScrollable;
  final List<Widget>? tabs;

  @override
  State<ITabBar> createState() => _ITabBarState();
}

class _ITabBarState extends State<ITabBar> {
  bool get canLoad {
    return widget.ctrl != null && widget.tabs?.isNotEmpty == true;
  }

  bool isLoaded = false;

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      _setup();
    });
  }

  @override
  void didUpdateWidget(covariant ITabBar oldWidget) {
    _setup();
    super.didUpdateWidget(oldWidget);
  }

  void _setup() async {
    if (isLoaded) return;
    if (widget.config?.indicator != null && canLoad) {
      final index = widget.ctrl!.index;
      widget.ctrl!.index = index == 0 ? 1 : index - 1;
      await Future.delayed(const Duration(milliseconds: 10));
      widget.ctrl!.index = index;
      isLoaded = true;
    }
  }

  @override
  Widget build(BuildContext context) {
    if (!canLoad) {
      return const SizedBox.shrink();
    }

    final c = widget.config ?? TabbarConfig.defalut();

    return Container(
      height: c.tabBarHeight,
      alignment: Alignment.centerLeft,
      decoration: BoxDecoration(
        color: c.backgroundColor,
        boxShadow: c.evaluate
            ? const [
                BoxShadow(
                    color: Colors.grey,
                    blurRadius: 3,
                    blurStyle: BlurStyle.outer),
              ]
            : null,
      ),
      child: TabBar(
        controller: widget.ctrl,
        indicatorColor: c.indicatorColor,
        indicatorWeight: c.indicatorWeight,
        isScrollable: widget.isScrollable,
        labelStyle: TextStyle(
          color: c.selectedTextColor,
          fontSize: c.selectedFontSize,
        ),
        unselectedLabelStyle: TextStyle(
          color: c.unSelectedTextColor,
          fontSize: c.unSelectedFontSize,
        ),
        padding: c.padding,
        indicator: c.indicator,
        indicatorSize: c.indicatorSize,
        indicatorPadding: c.indicatorPadding,
        dividerColor: c.dividerColor,
        dividerHeight: c.dividerHeight,
        tabs: widget.tabs!,
      ),
    );
  }
}
